<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * SimplyPost
 *
 * @author		Pascal Kriete
 * @package		SimplyPost
 * @copyright	Copyright (c) 2008, Pascal Kriete
 * @license 	http://www.gnu.org/licenses/lgpl.txt
 */

// ------------------------------------------------------------------------

/**
 * Topic Controller
 *
 * @package		SimplyPost
 * @subpackage	Topic
 * @category	Controller
 * @author		Pascal Kriete
 */

class Topic extends BaseController {

	/**
	 * Constructor
	 *
	 * @access	public
	 */
	function Topic()
	{
		parent::BaseController();
		$this->lang->load('topic');
		$this->load->helper('date');
	}
	
	// --------------------------------------------------------------------
	
	/**
	 * Has no real function - redirects
	 *
	 * @access	public
	 */
	function index()
	{
		$this->session->set_flashdata('msg', 'Topic does not exist.');
		redirect('/');
	}
	
	// --------------------------------------------------------------------

	/**
	 * Show specified topic
	 *
	 * @access	public
	 * @param	integer	topic id
	 */
	function view($id = -1)
	{
		if ($id == -1)
		{
			$this->session->set_flashdata('msg', 'Topic does not exist.');
			redirect('/');
		}
		
		$this->breadcrumb->from_db($id, 'topic');
		
		/* Grab category name and child names/ids */
		$this->load->model('post/Post_model', 'Post');
		$posts = $this->Post->get_posts($id);
		$top_info = $this->Post->get_info($id);

		set_title(ucfirst($top_info[0]['name']));

		if ($posts == FALSE) {
			$this_id = $top_info[0]['id'];
			$red_id = $top_info[0]['parent_id'];
			$this->load->model('Top_model', 'Topic');
			$this->Topic->delete($this_id);
			
			$this->session->set_flashdata('msg', 'Topic Empty - Deleted!');
			redirect('forum/view/'.$red_id);
		}
		
		$this->load->model('member/User_model', 'User');
		
		$data['posts'] = $posts;
		$data['info'] = $top_info[0];

		$this->load->view('list', $data);
	}
	
	// --------------------------------------------------------------------
	
	/**
	 * Add a new topic
	 *
	 * @access	public
	 * @param	integer	parent id
	 */
	function add($id)
	{
		set_title($this->lang->line('topic_create_title'));
		$this->breadcrumb->from_db($id, 'forum', 'Add Thread');
		
		$this->load->helper('form');
		$this->load->library('validation');
		$this->load->library('post_handler');
				
		$data = array(
			'form_target'	=> 'topic/add/'.$id,
			'submit_text'	=> 'Create',
			'success_msg'	=> 'Thread Added'
		);

		$this->post_handler->add_post($id, $data, TRUE);

	}
	
	// --------------------------------------------------------------------
	
	/**
	 * New post validation
	 *
	 * @access	private
	 * @param	string	topic id
	 * @return	bool
	 */
	function _plugins($text)
	{
		$answer = $this->plugin->post_submit($text);
		
		if ($answer[0] === FALSE)
		{
			$this->validation->set_message('plugins', $answer[1]);
			return FALSE;
		}
		else
		{
			$_POST['content'] = $answer[1];
			return TRUE;
		}
	}
}